<script lang="ts" setup>
import { Delete, Plus } from '@icon-park/vue-next'
import {} from 'vue'
import { columns } from './columns'
import EditDialog from './components/Edit.vue'
import PermissionEditDialog from './components/PermissionEdit.vue'
import { Menu, deleteMenuApi, getMenuListApi } from '/@/api/auth/menu'
import { QsPageWrapper } from '/@/components/QsPageWrapper'
import { QsTable } from '/@/components/QsTable'
import { deleteItem } from '/@/hooks/useDelete'

const editDialogRef = ref<InstanceType<typeof EditDialog>>()
const permissionEditDialogRef = ref<InstanceType<typeof PermissionEditDialog>>()
const multipleSelection = ref<(string | number)[]>([])
const handleSelectionChange = (val: Menu[]) => {
  multipleSelection.value = val.map((item) => item.id)
}
const dataSources = ref<Menu[]>([])
const expandRowKeys = ref<(string | number)[]>([])
const getMenuList = async () => {
  const { result } = await getMenuListApi()
  dataSources.value = result
  expandRowKeys.value = []
  const deep = (data: Menu[], level = 1) => {
    data.forEach((item) => {
      item.level = level
      if (item.children) {
        if (item.type === 1 && item.children.some((item) => item.type === 1)) {
          expandRowKeys.value.push(`${item.id}`)
        }
        const _level = level + 1
        deep(item.children, _level)
      }
    })
  }
  deep(result)
}

onBeforeMount(async () => {
  await getMenuList()
})
</script>

<template>
  <qs-page-wrapper :header="false" :query="true">
    <template #queryLeft>
      <el-button type="primary" @click="editDialogRef?.open({})">
        <template #icon>
          <plus />
        </template>
        添加
      </el-button>
      <el-button
        :disabled="!multipleSelection.length"
        type="danger"
        @click="() => deleteItem(deleteMenuApi, multipleSelection).then(getMenuList)"
      >
        <template #icon>
          <delete />
        </template>
        批量删除
      </el-button>
    </template>
    <qs-table
      :columns="columns"
      :data="dataSources"
      :expand-row-keys="expandRowKeys"
      row-key="id"
      :selection="true"
      :tree-props="{ children: 'children' }"
      @delete="(id) => deleteItem(deleteMenuApi, id).then(getMenuList)"
      @selection-change="handleSelectionChange"
      @show-edit="editDialogRef?.open"
      @show-sub-level="permissionEditDialogRef?.open"
    />
    <edit-dialog ref="editDialogRef" @refresh="getMenuList" />
    <permission-edit-dialog ref="permissionEditDialogRef" @refresh="getMenuList" />
  </qs-page-wrapper>
</template>

<style lang="scss" scoped></style>
